package mall

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"github.com/shopspring/decimal"
	"private-domain-overseas-service/app/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/status/bizmall"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzmallgoods"

	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallGoodsListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 推荐商品列表
func NewMallGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallGoodsListLogic {
	return &MallGoodsListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallGoodsListLogic) MallGoodsList(req *types.MallGoodsRequest) (resp *types.MallGoodsResponse, err error) {
	mallGoodsDao := mall.NewMallGoodsDao(l.ctx, l.svcCtx)

	//定义计算值
	baiDecimal := decimal.NewFromInt(100)

	//查询推荐商品
	mallGoodsConditions := make([]predicate.HzMallGoods, 0)
	mallGoodsConditions = append(mallGoodsConditions, hzmallgoods.GoodsStatusEQ(bizmall.On), hzmallgoods.GoodsMallIDEQ(req.MallId))
	mallGoods, total, err := mallGoodsDao.MallGoodsConditionsPageAll(req.Current, req.PageSize, mallGoodsConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询推荐商品数据失败：%v", err.Error()))
	}

	//组装返回数据
	lists := lo.Map(mallGoods, func(item *ent.HzMallGoods, _ int) *types.MallGoodsList {
		//到手价
		goodsReceivedPriceFen := decimal.NewFromInt(item.GoodsReceivedPrice)
		//原价
		goodsOriginalPriceFen := decimal.NewFromInt(item.GoodsOriginalPrice)
		//（原价 - 到手价）/原价
		discount := goodsOriginalPriceFen.Sub(goodsReceivedPriceFen).Div(goodsOriginalPriceFen).Mul(baiDecimal).StringFixed(2)
		return &types.MallGoodsList{
			Id:                 int64(item.ID),
			GoodsImage:         constant.MallGoodsImage + item.GoodsImage,
			GoodsTitle:         item.GoodsTitle,
			GoodsReceivedPrice: goodsReceivedPriceFen.Div(baiDecimal).StringFixed(2),
			GoodsOriginalPrice: goodsOriginalPriceFen.Div(baiDecimal).StringFixed(2),
			GoodsBuyUrl:        item.GoodsBuyURL,
			Discount:           discount,
			GoodsCommission:    decimal.NewFromInt(item.GoodsCommission).Div(baiDecimal).StringFixed(2),
		}
	})

	//返回组装数据
	resp = &types.MallGoodsResponse{
		Page: &types.PageResponse{
			Total:           total,
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
		List: lists,
	}
	return resp, nil

}
